﻿using System;

namespace EchoFramework
{
    /// <summary>
    /// 时间/帧数分发类，用于延迟调用
    /// </summary>
    public class Dispatcher
    {
        /// <summary>
        /// 分发枚举类型
        /// </summary>
        private DispatcherEnum dispatcherEnum = DispatcherEnum.None;

        /// <summary>
        /// 触发行为
        /// </summary>
        private Action dispatcherAction;

        /// <summary>
        /// 触发时间
        /// </summary>
        private float triggerTime;

        /// <summary>
        /// 触发帧数
        /// </summary>
        private int triggerFrame;

        /// <summary>
        /// 重置
        /// </summary>
        public void Reset()
        {
            dispatcherEnum = DispatcherEnum.None;
            dispatcherAction = null;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="dispatcherType">分发枚举</param>
        /// <param name="action">触发行为</param>
        /// <param name="delayTime">延时触发时间</param>
        /// <param name="delayFrame">延时触发帧数</param>
        public void Init(DispatcherEnum dispatcherType, Action action, float delayTime, int delayFrame)
        {
            dispatcherEnum = dispatcherType;
            dispatcherAction = action;
            triggerTime = TimeManager.TimeSeconedFloat + delayTime;
            triggerFrame = TimeManager.FrameSinceGameStart + delayFrame;
        }

        /// <summary>
        /// 检查满足条件后执行
        /// </summary>
        public bool CheckExecute()
        {
            if (dispatcherAction == null || dispatcherEnum == DispatcherEnum.None)
                return true;
            
            switch (dispatcherEnum)
            {
                case DispatcherEnum.Time:  //检测时间
                    if (TimeManager.TimeSeconedFloat >= triggerTime)
                    {
                        dispatcherAction?.Invoke();
                        return true;
                    }
                    break;
                case DispatcherEnum.Frame:  //检测帧数
                    if (TimeManager.FrameSinceGameStart >= triggerFrame)
                    {
                        dispatcherAction?.Invoke();
                        return true;
                    }
                    break;
            }

            return false;
        }
    }
}